package ca.bcit.comp_3512.assignment_02.data_managers;

import java.io.Serializable;
import java.util.List;

import javax.ejb.Stateful;
import javax.enterprise.context.ConversationScoped;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import ca.bcit.comp_3512.assignment_02.data_models.User;
import ca.bcit.comp_3512.assignment_02.data_models.WeeklyEntry;

@ConversationScoped
@Stateful
public class UserManager implements Serializable
{
    @PersistenceContext(unitName="cats_and_more_cats")
    EntityManager em;

    public User find(Integer userID)
    {
        return em.find(User.class, userID);
    }
    
    public void persist(User user)
    {
        em.persist(user);
    }
    
    public void merge(User user)
    {
        em.merge(user);
    }
    
    public void remove(User user)
    {
        em.remove(find(user.getUserID()));
    }
    
    public WeeklyEntry getWeeklyEntryByYearAndWeek(Integer userID, Integer year, Integer week)
    {
        TypedQuery<WeeklyEntry> query = em.createQuery("select w from weekly_entries w " + 
                                            " where w.user_id = " + userID +
                                            " and w.year = " + year +
                                            " and w.week = " + week +
                                            " group by w.year, w.week ", WeeklyEntry.class);
        return query.getSingleResult();
    }
    
    public User[] getByID(Integer userID)
    {
        TypedQuery<User> query = em.createQuery("select u from users u where u.user_id = " + userID, User.class);
        List<User> users = query.getResultList();
        User[] userArray = new User[users.size()];
        for (int i = 0; i < userArray.length; ++i)
        {
            userArray[i] = users.get(i);
        }
        return userArray;
    }
    
    public User[] getAll()
    {
        TypedQuery<User> query = em.createQuery("select u from User u", User.class);
        List<User> users = query.getResultList();
        User[] userArray = new User[users.size()];
        for (int i = 0; i < userArray.length; ++i)
        {
            userArray[i] = users.get(i);
        }
        return userArray;
    }
    
}
